(function(){
    angular.module('app').controller("agbAdvCtrl",function($scope,proxy,$stateParams) {
        $scope.permission = PERMISSION;
        $scope.isEditInfo = false;
        $scope.isEditPwd = false;
        $scope.industryOneList = [];
        $scope.industryTwoList = [];
        $scope.tab = 1;
        $scope.quaOtherList = []
        $scope.oem = JSON.parse(localStorage.oem)
        $scope.adv = {
            industryOne:"请选择行业大类",
            industryTwo:"请选择行业小类"
        };
        $scope.isDirect = isDirect;
        $scope.toggleTab = function(index){
            $scope.tab = index;
        }
        // 代理商密码对象
        $scope.pwd = {}
        // 广告主密码对象
        $scope.advPwd = {}
        // 利润对象
        $scope.profits = {
            type: "2",
            value: "",
            id:''
        }

        $scope.filter = {}

        // 显示利润设置弹框
        $scope.showProfits = function(item) {
            $scope.profits.value = (item.premium * 100).toFixed(2);
            $scope.profits.id = item.id;
            layer.open({
                type: 1,
                title: "利润设置",
                content: $('.profits'),
                area:["","250px"]
            })
        }

        // 设置广告主利润率
        $scope.profitSet = function() {
            var premium = ($scope.profits.value /100).toFixed(4),
                id = $scope.profits.id;
                if(premium < 0) return layer.msg("利润必须大于等于0！")
                if(premium > $scope.premiumMax) return layer.msg("利润设置不能超过"+($scope.premiumMax*100)+"%")
            var data = {
                id: id,
                premium: premium
            };
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/finance/profit/set',
                load: true,
                data: data,
                success: function(){
                    layer.closeAll();
                    getAdvList();
                }
            })
        }
        //提示信息显示
        $scope.tips = function (event) {
            layer.tips("进行溢价设置需要满足以下条件：1 广告主余额为0；2 广告主暂停6小时以上；3 广告主合约订单执行完毕", $(event.target), {
                time: 0,
                tips: [1, '#fffee3'] //还可配置颜色
            });
        }

        // 显示修改广告主密码弹框
        $scope.showRePwd = function(id) {
            $scope.advPwd = {
                id:id
            }
            layer.open({
                type: 1,
                title: "重置密码",
                content: $('.rePwd'),
                area:["","280px"]
            })
        }
        // 显示新建广告主弹框
        $scope.newAdv = function() {
            $scope.adv = {
                "type": "3",
                title: "新建广告主",
                roleName: "请绑定角色",
                premium: "0",
                domainTitle:"请选择域名",
                industryOne:"请选择行业大类",
                industryTwo:"请选择行业小类"
            }
            if($scope.isDirect == 1) {
                $scope.adv.roleID = "2";
                // 直客账户仅允许创建一个广告主
                if($scope.list.length == 1) return;
            }
            $("#advModal").modal()
        }
        // 显示修改广告主弹框
        $scope.updateAdv = function(id,canSetPremiun) {
            var data = {
                'id': id
            };
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/advertiser',
                load: true,
                data: data,
                success: function(res){
                    // 获得列表
                    var adv = res.data;
                    $scope.adv = {
                        id: adv.id,
                        name: adv.name,
                        address: adv.address,
                        brand: adv.brand,
                        contacts: adv.contacts,
                        wwwUrl: adv.wwwUrl,
                        shortName: adv.shortName,
                        parentIndustry: adv.parentIndustry,
                        industry: adv.industry,
                        telephone: adv.telephone,
                        roleID: adv.roleID,
                        domain: adv.domain,
                        domainTitle: adv.domain,
                        canSetPremiun: canSetPremiun,
                    }
                    $scope.industryOneList.forEach(function(v){
                        if(v.id == adv.parentIndustry) {
                            $scope.adv.industryOne = v.name;
                            $scope.industryTwoList = v.subType;
                            v.subType.forEach(function(sv){
                                if(sv.id == adv.industry) {
                                    $scope.adv.industryTwo = sv.name;
                                    return false;
                                }
                            })
                            return false;
                        }
                    })

                    var $adv = $scope.adv;
                    $adv.title = "编辑广告主";
                    $adv.roleName = "请绑定角色";
                    if($adv.roleID) {
                        $scope.roleList.forEach(function(v){
                            if(v.id == $adv.roleID) {
                                $adv.roleID = v.id;
                                $adv.roleName = v.name;
                                return false;
                            }
                        })
                    }

                    $("#advModal").modal()
                }
            })
        }

        $scope.updateDomain = function(id) {
            var data = {
                'id': id
            };
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/advertiser',
                load: true,
                data: data,
                success: function(res){
                    // 获得列表
                    var adv = res.data;
                    $scope.adv = {
                        domainTitle: adv.domain,
                        domain: adv.domain,
                        id: adv.id,
                    }
                    $("#domainModal").modal()
                }
            })
        }
        $scope.editDomain = function() {
            var adv = $scope.adv;
            if(!adv.domain) return layer.msg("请选择域名!");

            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/advertiser/modify',
                load:true,
                data: {
                    data: adv
                },
                success: function(res){
                    layer.msg("操作成功!");
                    $("#domainModal").modal("hide");
                }
            })
        }

        // 跳转资质上传界面
        $scope.showQua = function(id) {
            location.href = "#/agentBg/"+$stateParams.agentID+"/manage/"+id+"/"+$(".page .focus").html()+"/qualification"
        }

        // 重置广告主密码
        $scope.resetAdvPWD = function(pwd) {
            if(pwd.passWord != pwd.passWord2) return layer.msg("两次密码不一致!");
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/reset/adv/passwd',
                load:true,
                data: {
                    id: pwd.id,
                    newPasswd: pwd.passWord
                },
                success: function(){
                    layer.closeAll();
                    layer.msg("修改成功!");

                }
            })
        }

        // 添加/编辑广告主
        $scope.addAdv = function() {
            var adv = angular.copy($scope.adv),
                domainReg = /^https?:\/\//,
                phoneReg = /^1\d{10}$/;
            adv.type = "3";
            // adv.roleID = "2";
            var err = advCheck();
            if (err) {
                return layer.msg(err);
            }
            if(!adv.industry) return layer.msg("请选择行业!");
            if(!adv.roleID) return layer.msg("请选择角色!");
            // 域名存在时判断是否选择了域名
            if($scope.domainList.length > 0 && !adv.domain) return layer.msg("请选择域名!");
            if(adv.passWord != adv.passWord2) return layer.msg("两次密码不相同!");
            if(!domainReg.test(adv.wwwUrl)) return layer.msg("公司网站格式有误!必须以http://或者https://开头");
            if(!phoneReg.test(adv.telephone)) return layer.msg("手机号码格式有误!");

            // 判断是否为新建
            if(!adv.id) {
                if(!adv.premium || adv.premium < 0) return layer.msg("利润必须大于等于0！")
                if(adv.premium > $scope.premiumMax*100) return layer.msg("利润设置不能超过"+($scope.premiumMax*100)+"%")
                
                adv.premium = adv.premium/100+"";
            }
            adv.canSetPremiun = null;
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/advertiser/' + (adv.id?"modify":"add"), // id存在修改  不存在添加
                load:true,
                data: {
                    data: adv
                },
                success: function(res){
                    layer.msg("操作成功!");
                    $("#advModal").modal("hide");
                    getAdvList();
                }
            })
        }

        // 开启/关闭广告主
        $scope.setStatus = function (item) {
            var adv = {
                id: item.id,
                state: item.open?"10":"30"
            }
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/advertiser/modify',
                load:true,
                data: {
                    data:adv
                },
                success:function(){
                    item.state = item.state == "10"?"20":"10";
                },
                error: function () {
                    // 失败时,将switch状态重置
                    item.open = !item.open
                }
            })
        }
        // 选择角色
        $scope.selectRole = function(item) {
            $scope.adv.roleID = item.id;
        }
        // 选择域名
        $scope.selectDomain = function(item) {
            $scope.adv.domain = item.name;
        }

        // 选择行业大类
        $scope.selectOne = function(item) {
            $scope.industryTwoList = item.subType;
            $scope.adv.parentIndustry = item.id;
        }
        // 选择行业小类
        $scope.selectTwo = function(item) {
            $scope.adv.industry = item.id;
        }
        // 根据名字查询
        $scope.search = function (value) {
            $scope.filter.name = value;
            getAdvList();
        }

        function getAdvList(current, pagesize) {
            var data = {
                'page': (current || 1)+"",
                'size': (pagesize || 20)+"",
                'filter': $scope.filter,
                "sort": ["cTime,1"],
            };
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/advertiser/list',
                load: true,
                data: data,
                success: function(res){
                    // 获得列表
                    if (res.data)
                        $scope.list = res.data.data || [];
                    else 
                        $scope.list = [];
                    $("#pageToolbar").html("");
                    $('#pageToolbar').Paging({
                        pagesize: pagesize || '20',
                        current: current || '1',
                        count:res.data.total,
                        toolbar:true,
                        'hash': false,
                        callback:getAdvList
                    });
                }
            })
        }
        // 获得角色列表
        function getRoleList() {
            var data = {
                'page': "1",
                'size': "99999",
                "sort": ["cTime,1"],
                filter: {
                    roleType: '1'
                },
                sTime : $scope.sTime,
                eTime : $scope.eTime
            };
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/pri/role/list',
                load: true,
                data: data,
                success: function(res){
                    // 获得列表
                    $scope.roleList = res.data.data;
                }
            })
        }
        // 获得行业分类
        function getIndustry () {
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/industry/type',
                load: true,
                data: {},
                success: function(res){
                    // 获得列表
                    $scope.industryOneList = res.data;

                }
            })
        }
        //check广告主
        function advCheck() {
            var adv = $scope.adv,
                error;
            if (!adv.loginName && !adv.id) {
                return error = "请输入账户名。";
            }
            if (!adv.passWord && !adv.id) {
                return error = "请输入密码。";
            }
            if (!adv.passWord2 && !adv.id) {
                return error = "请输入二次密码。";
            }
            if (!adv.wwwUrl) {
                return error = "请输入公司网站。";
            }
            if (!adv.name) {
                return error = "请输入公司名称。";
            }
            if (!adv.brand) {
                return error = "请输入品牌。";
            }
            if (!adv.contacts) {
                return error = "请输入联系人。";
            }
            if (!adv.telephone) {
                return error = "请输入手机号。";
            }
            if (!adv.address) {
                return error = "请输入公司地址。";
            }
        }
        
        function getPremiumMax () {
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/sys/parameter/query',
                load: true,
                data: {
                    "filter":{"feature":"dsp.feature.agency.advertiser.profix.maxvalue"}
                },
                success: function(res){
                    $scope.premiumMax = res.data[0].value*1 || 0.6;
                }
            })
        }

        function getDomain () {
            // 获取orgID
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/UserInfo',
                data: {
                    type: userType
                },
                success: function(res){
                    var orgID = res.data.orgID;

                    // 获取域名列表
                    proxy.proxy({
                        url: STATIC_URL.domian+'/dsp/user/oem/url/list',
                        data: {
                            filter: {
                                orgID: orgID
                            }
                        },
                        success: function(res){
                            var arr = res.data || [];
                            for(var i = 0; i < arr.length; i++) {
                                var domain = arr[i];
                                arr[i] = {
                                    name: domain
                                }
                            }
                            // 获得列表
                            $scope.domainList = arr;
                        }
                    })
                }
            })
        }

        getAdvList();
        getIndustry();
        getRoleList();
        getPremiumMax();
        getDomain();
    })
})();